package com.ja.openchat.ui.found;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.dueeeke.videoplayer.player.VideoView;
import com.github.chrisbanes.photoview.OnPhotoTapListener;
import com.github.chrisbanes.photoview.PhotoView;
import com.google.gson.JsonObject;
import com.gyf.immersionbar.ImmersionBar;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.ui.chat.ForwardActivity;
import com.ja.openchat.ui.chat.GoChatPicEditActivity;
import com.ja.openchat.ui.chat.MessageViewModel;
import com.ja.openchat.views.CustomStandardVideoController;
import com.ja.openchat.views.FingerViewGroup;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.nanchen.compresshelper.CompressHelper;
import com.vachel.editor.PictureEditActivity;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.circle.BlogInfo;
import com.zy.openchat.core.model.file.FileInfo;
import com.zy.openchat.core.model.file.FileTaskInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.photo.PhotoInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.core.model.video.UploadMedioInfo;
import com.zy.openchat.core.model.video.VideoInfo;
import com.zy.openchat.util.Common;
import com.zy.openchat.util.SingleMediaScanner;
import com.zy.openchat.util.glide.GlideApp;
import com.zy.openchat.util.share.GoShare;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okio.BufferedSource;
import okio.Okio;
import okio.Sink;

/**
 * @author imndx
 */
public class PreviewCircleMediaActivity extends JaBaseActivity {
    private SparseArray<View> views;
    private View currentVideoView;
    private ViewPager viewPager;
    private MMPagerAdapter adapter;
    private BlogInfo mBlogInfo;
    private int currentPosition = -1;
    private List<Object> entries;
    private boolean pendingPreviewInitialMedia;

    private class MMPagerAdapter extends PagerAdapter {
        private List<Object> entries;

        public MMPagerAdapter(List<Object> entries) {
            this.entries = entries;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            View view;
            Object entry = entries.get(position);
            if (entry instanceof PhotoInfo) {
                view = LayoutInflater.from(PreviewCircleMediaActivity.this).inflate(R.layout.preview_photo, null);
            } else {
                view = LayoutInflater.from(PreviewCircleMediaActivity.this).inflate(R.layout.preview_video, null);
            }
            view.setTag(position);
            container.addView(view);
            views.put(position % 3, view);
            if (pendingPreviewInitialMedia) {
                preview(view, entry);
            }
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, @NonNull Object object) {
            // do nothing ?
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return entries == null ? 0 : entries.size();
        }

        public Object getEntry(int position) {
            return entries.get(position);
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }
    }

    final ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            // TODO 可以在此控制透明度
        }

        @Override
        public void onPageSelected(int position) {
            View view = views.get(position % 3);
            if (view == null) {
                // pending layout
                return;
            }
            if (currentVideoView != null) {
                resetVideoView(currentVideoView);
                currentVideoView = null;
            }
            setCurrentTitle(position);
            Object entry = adapter.getEntry(position);
            preview(view, entry);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private boolean isImageType(Object message){
        if(message==null){
            return false;
        }
        return message instanceof PhotoInfo;
    }

    private void preview(View view, Object message) {

        if (isImageType(message)) {
            previewImage(view, message);
        } else {
            previewVideo(view, message);
        }
    }

    private void resetVideoView(View view) {
        PhotoView photoView = view.findViewById(R.id.photoView);
        VideoView videoView = view.findViewById(R.id.videoView);

        photoView.setVisibility(View.VISIBLE);
        videoView.pause();
    }

    private void previewVideo(View view, Object entry) {

        PhotoView photoView = view.findViewById(R.id.photoView);

        if(entry instanceof VideoInfo){
            VideoInfo videoInfo = (VideoInfo) entry;
            if(videoInfo.isVideo()){
                if(videoInfo.isVideoDownloaded()){
                    Glide.with(this)
                            .load(videoInfo.localVideoPath())
                            .into(photoView);
                }else{
                    if(!videoInfo.isVideoDownloadComplete()){
                        TelegramManager.getTelegramManager().downloadFile("blog_" + mBlogInfo.id, videoInfo.getVideoFileId(),videoInfo.downloadedStart(), TelegramManager.FileType.FileType_Message_Video);
                    }
                }
            }else{
                if(videoInfo.isAnimationDownloaded()){
                    Glide.with(this)
                            .load(videoInfo.localAnimationPath())
                            .into(photoView);
                }else{
                    if(!videoInfo.isAnimationDownloadComplete()){
                        TelegramManager.getTelegramManager().downloadFile("blog_" + mBlogInfo.id
                                , videoInfo.getAnimationFileId(), videoInfo.donwloadAnimationStart()
                                , TelegramManager.FileType.FileType_Message_Video);
                    }
                }
            }

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(videoInfo.isVideo()){
                        if (videoInfo.isVideoDownloaded()) {
                            playVideo(view, videoInfo.localVideoPath());
                        }
                    }else{
                        if (videoInfo.isAnimationDownloaded()) {
                            playVideo(view, videoInfo.localAnimationPath());
                        }
                    }

                }
            });
        }

        if(isFirstShow){
            isFirstShow = false;
            view.post(new Runnable() {
                @Override
                public void run() {
                    if(view!=null){
                        view.performClick();
                    }
                }
            });
        }

    }

    private boolean isFirstShow = true;

    private void playVideo(View view, String videoUrl) {
        VideoView videoView = view.findViewById(R.id.videoView);
        PhotoView photoView = view.findViewById(R.id.photoView);
        photoView.setVisibility(View.GONE);
        currentVideoView = view;

        videoView.setVisibility(View.VISIBLE);
        videoView.setUrl(videoUrl); //设置视频地址
        if(videoView.getTag(R.id.cacheControllerKey)==null){
            CustomStandardVideoController controller = new CustomStandardVideoController(this);
            controller.addDefaultControlComponent("预览");
            controller.setEnableOrientation(true);
            videoView.setVideoController(controller); //设置控制器
            videoView.setTag(R.id.cacheControllerKey,controller);
        }

        long position = -1;
        if(videoView.isPlaying()){
            position = videoView.getCurrentPosition();
        }
        videoView.start(); //开始播放，不调用则不自动播放
        if(position>0){
            videoView.seekTo(position);
        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event){
        if((tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_Message_Preview_Photo_Ok
                ||tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_Message_Video_Ok)&&tg_event.data instanceof FileTaskInfo &&tg_event.dataEx instanceof FileInfo){
            FileInfo fileInfo = (FileInfo) tg_event.dataEx;
            String ids = ((FileTaskInfo)tg_event.data).id;
            if(!TextUtils.isEmpty(ids)&&ids.contains("_")) {
                String[] idArray = ids.split("_");
                if (idArray.length >= 2&&"blog".equals(idArray[0])&&idArray[1].equals(String.valueOf(mBlogInfo.id))) {
                    for (int i = 0; i < adapter.getCount(); i++) {
                        Object message = adapter.getEntry(i);
                        if (isImageType(message)) {
                            PhotoInfo photoInfo = (PhotoInfo) message;
                            if(photoInfo.getPhotoFileId() == fileInfo.id){
                                photoInfo.updatePhotoFile(fileInfo);
                                View view = viewPager.findViewWithTag(i);
                                if(view!=null){
                                    preview(view,message);
                                }
                                break;
                            }

                        }else{
                            VideoInfo videoInfo = (VideoInfo) message;
                            if(videoInfo.getVideoFileId() == fileInfo.id){
                                videoInfo.updateVideoFile(fileInfo);
                                View view = viewPager.findViewWithTag(i);
                                if(view!=null){
                                    playVideo(view,videoInfo.localVideoPath());
                                }
                                break;
                            }

                        }
                    }
                }
            }
        }
    }

    @Override
    protected boolean isHaveEventBus() {
        return true;
    }

    private void previewImage(View view, Object entry) {
        PhotoView photoView = view.findViewById(R.id.photoView);
        photoView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                iv_bar_right.performClick();
                return false;
            }
        });
        PhotoInfo photoInfo = (PhotoInfo) entry;
        if(photoInfo.isPhotoDownloaded()){
            Glide.with(this)
                    .load(photoInfo.getPhotoImagePath())
                    .into(photoView);
        }else{
            TelegramManager.getTelegramManager().downloadFile("blog_" + mBlogInfo.id, photoInfo.getPhotoFileId()
                    , 0, TelegramManager.FileType.FileType_Message_Photo);
        }
        photoView.setOnPhotoTapListener(new OnPhotoTapListener() {
            @Override
            public void onPhotoTap(ImageView view, float x, float y) {
                finish();
            }
        });
    }


    private TextView tv_bar_title;
    private AppCompatImageView iv_bar_right;

    @Override
    public void setStatusBar() {
        BarUtils.setStatusBarLightMode(this, false);
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
        BarUtils.subtractMarginTopEqualStatusBarHeight(findViewById(R.id.ad_finger_vg));
//        StatusBarUtil.setMargin(this, findViewById(R.id.toolbar));
    }

    @Override
    public void initData() {
        if (getIntent() != null) {
            mBlogInfo = getIntent().getParcelableExtra("blogInfo");
            currentPosition = getIntent().getIntExtra("current",0);
        }
        if(mBlogInfo==null){
            finish();
            return;
        }
        entries = mBlogInfo.getMedioInfos();
        if(Common.isEmpty(entries)){
            finish();
            return;
        }

        views = new SparseArray<>(3);
        viewPager = findViewById(R.id.viewPager);
        adapter = new MMPagerAdapter(entries);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(1);
        viewPager.addOnPageChangeListener(pageChangeListener);
        tv_bar_title = findViewById(R.id.tv_bar_title);

        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setBackgroundResource(R.drawable.transparent_shape);
        ((ViewGroup.MarginLayoutParams)toolbar.getLayoutParams()).topMargin = ImmersionBar.getStatusBarHeight(this);
        tv_bar_title.setTextColor(ContextCompat.getColor(this,R.color.white));
        iv_bar_right = findViewById(R.id.iv_bar_right);
        iv_bar_right.setImageResource(R.mipmap.gengduo_preview);
        iv_bar_right.setVisibility(View.VISIBLE);
        iv_bar_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int currentIndex = viewPager.getCurrentItem();
                final String[] popuTitles;
                if(entries!=null&&entries.size()>currentIndex&&isImageType(entries.get(currentIndex))){
                    popuTitles = new String[]{getString(R.string.save_album),getString(R.string.share_text),getString(R.string.edit_text),getString(R.string.forward_text),getString(R.string.collect_text)};
                }else{
                    popuTitles = new String[]{getString(R.string.save_album), getString(R.string.share_text),getString(R.string.forward_text),getString(R.string.collect_text)};
                }
                new XPopup.Builder(PreviewCircleMediaActivity.this).asBottomList(null, popuTitles, new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        int currentIndex = viewPager.getCurrentItem();
                        if(entries!=null&&entries.size()>currentIndex){
                            Object messageInfo = entries.get(currentIndex);
                            String filePath = null;
                            boolean isDownloadCompleted = false;
                            if(isImageType(messageInfo)){
                                PhotoInfo photoInfo = (PhotoInfo) messageInfo;
                                if(photoInfo.isPhotoDownloaded()){
                                    filePath = photoInfo.getPhotoImagePath();
                                    isDownloadCompleted = true;
                                }
                            }else{
                                VideoInfo videoInfo = (VideoInfo) messageInfo;
                                if(videoInfo.isVideoDownloaded()){
                                    filePath = videoInfo.localVideoPath();
                                }
                                isDownloadCompleted = videoInfo.isVideoDownloadComplete();
                            }
                            if(TextUtils.isEmpty(filePath)){
                                ToastUtils.showShort(getString(R.string.downloading_try_again));
                                return;
                            }
                            if(position == 1){
                                if(!isDownloadCompleted){
                                    ToastUtils.showShort(getString(R.string.downloading_try_again));
                                    return;
                                }
                                new GoShare.FShareBuilder(PreviewCircleMediaActivity.this, App.getInstanse().getPackageName() + ".utilcode.fileprovider")
                                        .setFilePath(filePath)
                                        .setShareSubject(getResources().getString(R.string.app_name))
                                        .build()
                                        .shareByCustom();

                            }else if(position == 0){
                                if(!isDownloadCompleted){
                                    ToastUtils.showShort(getString(R.string.downloading_try_again));
                                    return;
                                }
                                if(isImageType(messageInfo)){
                                    try {
                                        MediaStore.Images.Media.insertImage(getContentResolver(), filePath, getResources().getString(R.string.app_name), getResources().getString(R.string.app_name));
                                    } catch (FileNotFoundException e) {
                                        e.printStackTrace();
                                    }
                                    new SingleMediaScanner(getApplicationContext(), filePath, new SingleMediaScanner.ScanListener() {
                                        @Override
                                        public void onScanFinish() {
                                            ToastUtils.showShort(getString(R.string.save_album_success));
                                        }
                                    });

                                }else{
                                    try {
                                        saveVideo(PreviewCircleMediaActivity.this,new File(filePath));
//                                        insertVideo(filePath,PreviewMediaActivity.this);
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }

                                }
                            }else if((position == 2&&popuTitles.length==5)){
                                Intent intent = new Intent();
                                intent.putExtra(PictureEditActivity.EXTRA_IMAGE_URI, Uri.fromFile(new File(filePath)));
                                intent.putExtra(PictureEditActivity.EXTRA_TYPE,1);
                                intent.setClass(PreviewCircleMediaActivity.this, GoChatPicEditActivity.class);
                                PreviewCircleMediaActivity.this.startActivity(intent);
                            }else if((position == 2&&popuTitles.length==4)||(position == 3&&popuTitles.length==5)){
                                Intent intent = new Intent(PreviewCircleMediaActivity.this, ForwardActivity.class);
                                if(messageInfo instanceof PhotoInfo){
                                    intent.putExtra(ForwardActivity.BUNDLE_REMOTE_PHOTO,(PhotoInfo)messageInfo);
                                }else if(messageInfo instanceof VideoInfo){
                                    intent.putExtra(ForwardActivity.BUNDLE_REMOTE_VIDEO,(VideoInfo)messageInfo);
                                }else{
                                    intent.putExtra(ForwardActivity.BUNDLE_OUTER_PATH,filePath);
                                }

                                PreviewCircleMediaActivity.this.startActivity(intent);
                            }else if((position == 3&&popuTitles.length==4)||(position == 4&&popuTitles.length==5)){
                                showProgress();
                                final String localPath = filePath;
                                TelegramManager.getTelegramManager().createPrivateChat(PreviewCircleMediaActivity.this, UserInfo.getUserInfo().id, new TgResultBlock<ChatInfo>() {
                                    @Override
                                    public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                                        if (obj != null) {
                                            sendMedia(messageInfo,localPath,obj);
                                        }else{
                                            hideProgress();
                                            ToastUtils.showShort(getString(R.string.request_error));
                                        }
                                    }

                                    @Override
                                    public void onTimeout(Map<String, Object> request) {
                                        hideProgress();
                                        ToastUtils.showShort(getString(R.string.request_error));
                                    }
                                });
                            }
                        }

                    }
                }).show();
            }
        });
        AppCompatImageView iv_bar_back = findViewById(R.id.iv_bar_back);
        iv_bar_back.setImageResource(R.mipmap.com_nav_ic_back_white_normal);
        iv_bar_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (currentPosition == 0) {
            viewPager.post(() -> {
                pageChangeListener.onPageSelected(0);
            });
            setCurrentTitle(0);
        } else {
            viewPager.setCurrentItem(currentPosition);
            pendingPreviewInitialMedia = true;
            setCurrentTitle(currentPosition);
        }

        FingerViewGroup adFingerViewGroup = findViewById(R.id.ad_finger_vg);
        adFingerViewGroup.setOnAlphaChangeListener(new FingerViewGroup.onAlphaChangedListener() {
            @Override
            public void onAlphaChanged(float alpha) {
                Log.e("fengan","[onAlphaChanged]:alpha="+alpha);
            }

            @Override
            public void onTranslationYChanged(float translationY) {
                Log.e("fengan","[onTranslationYChanged]:translationY="+translationY);
            }

            @Override
            public void onFinishAction() {
                finish();
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }
        });


    }
    private MessageViewModel messageViewModel;
    private void sendMedia(Object messageInfo ,String localPah,ChatInfo chatInfo){
        if(messageViewModel==null){
            messageViewModel = new MessageViewModel();
        }
        if(messageInfo instanceof PhotoInfo){
            messageViewModel.sendRemotePhoto(chatInfo, (PhotoInfo) messageInfo, new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    hideProgress();
                    ToastUtils.showShort(getString(R.string.collection_success));
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    hideProgress();
                    ToastUtils.showShort(getString(R.string.request_error));
                }
            });
        }else if(messageInfo instanceof VideoInfo){
            messageViewModel.sendVideoMsg(chatInfo,(VideoInfo) messageInfo,new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    hideProgress();
                    ToastUtils.showShort(getString(R.string.collection_success));
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    hideProgress();
                    ToastUtils.showShort(getString(R.string.request_error));
                }
            });
        }else{
            Observable.create(new ObservableOnSubscribe<UploadMedioInfo>() {

                @Override
                public void subscribe(@NonNull ObservableEmitter<UploadMedioInfo> emitter) throws Exception {
                    if(isImageType(messageInfo)){
                        File newFile = new CompressHelper.Builder(PreviewCircleMediaActivity.this).setMaxWidth(1440).setMaxHeight(2880).build().compressToFile(new File(localPah));
                        emitter.onNext(UploadMedioInfo.newImage(newFile.getAbsolutePath()));
                    }else{
                        emitter.onNext(UploadMedioInfo.newVideo(PreviewCircleMediaActivity.this,localPah));
                    }
                    emitter.onComplete();
                }
            }).subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<UploadMedioInfo>() {
                        @Override
                        public void accept(UploadMedioInfo uploadMedioInfo) throws Exception {
                            if(uploadMedioInfo.isImage){
                                GlideApp.with(PreviewCircleMediaActivity.this)
                                        .asBitmap()
                                        .load(uploadMedioInfo.mediaPath)
                                        .into(new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                                messageViewModel.sendImgMsg(chatInfo,uploadMedioInfo.mediaPath,resource,resource.getWidth(),resource.getHeight());
                                            }
                                        });
                            }else{
                                messageViewModel.sendVideoMsg(chatInfo,uploadMedioInfo.mediaPath,uploadMedioInfo.duration,uploadMedioInfo.width,uploadMedioInfo.height);
                            }
                            hideProgress();
                            ToastUtils.showShort(getString(R.string.collection_success));

                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            hideProgress();
                            ToastUtils.showShort(getString(R.string.request_error));
                        }
                    });
        }

    }

    private static final String VIDEO_BASE_URI = "content://media/external/video/media";

    private void insertVideo(String videoPath, Context context) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(videoPath);
        int nVideoWidth = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
        int nVideoHeight = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
        int duration = Integer
                .parseInt(retriever
                        .extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
        long dateTaken = System.currentTimeMillis();
        File file = new File(videoPath);
        String title = file.getName();
        String filename = file.getName();
        String mime = "video/mp4";
        ContentValues mCurrentVideoValues = new ContentValues(9);
        mCurrentVideoValues.put(MediaStore.Video.Media.TITLE, title);
        mCurrentVideoValues.put(MediaStore.Video.Media.DISPLAY_NAME, filename);
        mCurrentVideoValues.put(MediaStore.Video.Media.DATE_TAKEN, dateTaken);
        mCurrentVideoValues.put(MediaStore.MediaColumns.DATE_MODIFIED, dateTaken / 1000);
        mCurrentVideoValues.put(MediaStore.Video.Media.MIME_TYPE, mime);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//            String newPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + File.separator +paramFile.getName();
//            try {
//                fileCopy(paramFile.getAbsolutePath(),newPath);
//            }catch (Exception e){
//                e.printStackTrace();
//            }
            mCurrentVideoValues.put(MediaStore.Video.Media.RELATIVE_PATH, videoPath);
        }else{
            mCurrentVideoValues.put(MediaStore.Video.Media.DATA, videoPath);
        }
//        mCurrentVideoValues.put(MediaStore.Video.Media.DATA, videoPath);
        mCurrentVideoValues.put(MediaStore.Video.Media.WIDTH, nVideoWidth);
        mCurrentVideoValues.put(MediaStore.Video.Media.HEIGHT, nVideoHeight);
        mCurrentVideoValues.put(MediaStore.Video.Media.RESOLUTION, Integer.toString(nVideoWidth) + "x" + Integer.toString(nVideoHeight));
        mCurrentVideoValues.put(MediaStore.Video.Media.SIZE, new File(videoPath).length());
        mCurrentVideoValues.put(MediaStore.Video.Media.DURATION, duration);
        ContentResolver contentResolver = context.getContentResolver();
        Uri videoTable = Uri.parse(VIDEO_BASE_URI);
        Uri uri = contentResolver.insert(videoTable, mCurrentVideoValues);
        writeFile(videoPath, mCurrentVideoValues, contentResolver, uri);
    }

    private void writeFile(String imagePath, ContentValues values, ContentResolver contentResolver, Uri item) {
        try (OutputStream rw = contentResolver.openOutputStream(item, "rw")) {
            // Write data into the pending image.
            Sink sink = Okio.sink(rw);
            BufferedSource buffer = Okio.buffer(Okio.source(new File(imagePath)));
            buffer.readAll(sink);
            values.put(MediaStore.Video.Media.IS_PENDING, 0);
            contentResolver.update(item, values, null, null);
            new File(imagePath).delete();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Cursor query = getContentResolver().query(item, null, null, null);
                if (query != null) {
                    int count = query.getCount();
                    Log.e("writeFile","writeFile result :" + count);
                    query.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 保存视频
     * @param context
     * @param file
     */
    public static void saveVideo(Context context, File file) {
        //是否添加到相册
        ContentResolver localContentResolver = context.getContentResolver();
        long paramLong =  System.currentTimeMillis();
        ContentValues localContentValues = new ContentValues();
        localContentValues.put("title", file.getName());
        localContentValues.put("_display_name", file.getName());
        localContentValues.put("mime_type", "video/mp4");
        localContentValues.put("datetaken", Long.valueOf(paramLong));
        localContentValues.put("date_modified", Long.valueOf(paramLong));
        localContentValues.put("date_added", Long.valueOf(paramLong));
        String newPath;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            newPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator +file.getName();
            try {
                fileCopy(file.getAbsolutePath(),newPath);
            }catch (Exception e){
                e.printStackTrace();
            }
            localContentValues.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_MOVIES+ File.separator +file.getName());
        }else{
            newPath = file.getAbsolutePath();
            localContentValues.put("_data", file.getAbsolutePath());
        }

        localContentValues.put("_size", Long.valueOf(file.length()));
        Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri));

        new SingleMediaScanner(context.getApplicationContext(), newPath, new SingleMediaScanner.ScanListener() {
            @Override
            public void onScanFinish() {
                ToastUtils.showShort(context.getString(R.string.save_album_success));
            }
        });
    }

    public static boolean fileCopy(String oldFilePath,String newFilePath) throws IOException {
        //如果原文件不存在
        if(fileExists(oldFilePath) == false){
            return false;
        }
//        if(fileExists(newFilePath)==false){
//            new File(newFilePath).createNewFile();
//        }
        //获得原文件流
        FileInputStream inputStream = new FileInputStream(new File(oldFilePath));
        byte[] data = new byte[1024];
        //输出流
        FileOutputStream outputStream =new FileOutputStream(new File(newFilePath));
        //开始处理流
        while (inputStream.read(data) != -1) {
            outputStream.write(data);
        }
        inputStream.close();
        outputStream.close();
        return true;
    }

    public static boolean fileExists(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }


    private void setCurrentTitle(int currentIndex){
        if(entries!=null&&entries.size()>currentIndex&&isImageType(entries.get(currentIndex))){
            tv_bar_title.setText(String.format("%d/%d",currentIndex+1,entries.size()));
        }else{
            tv_bar_title.setText("");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(currentVideoView!=null&&currentVideoView.findViewById(R.id.videoView)!=null){
            ((VideoView)currentVideoView.findViewById(R.id.videoView)).pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(currentVideoView!=null&&currentVideoView.findViewById(R.id.videoView)!=null){
            ((VideoView)currentVideoView.findViewById(R.id.videoView)).resume();
        }

    }

//    @Override
//    public void onBackPressed() {
//        if(currentVideoView!=null&&currentVideoView.findViewById(R.id.videoView)!=null){
//            if (!((VideoView)currentVideoView.findViewById(R.id.videoView)).onBackPressed()) {
//                super.onBackPressed();
//            }
//        }
//    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        entries = null;
        if(currentVideoView!=null&&currentVideoView.findViewById(R.id.videoView)!=null){
            ((VideoView)currentVideoView.findViewById(R.id.videoView)).release();
        }
    }

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_mm_preview_circle;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    public static void previewMedia(Context context, BlogInfo entries, int current) {
        if (entries == null) {
            Log.w(PreviewCircleMediaActivity.class.getSimpleName(), "message is null or empty");
            return;
        }
        Intent intent = new Intent(context, PreviewCircleMediaActivity.class);
        intent.putExtra("blogInfo",entries);
        intent.putExtra("current",current);
        context.startActivity(intent);
    }


}
